package com.ysd.lis.service.emr.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import com.ysd.common.Result;
import com.ysd.lis.entity.SysUser;
import com.ysd.lis.entity.emr.*;
import com.ysd.lis.mapper.emr.EmrProcessMapper;
import com.ysd.lis.service.emr.EmrItemStandardTaskService;
import com.ysd.lis.service.emr.EmrProcessDetailService;
import com.ysd.lis.service.emr.EmrProcessDetailUserService;
import com.ysd.lis.service.emr.EmrProcessService;
import com.ysd.util.RedisUserManager;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author wh
 * @since 2025-06-07
 */
@Service
public class EmrProcessServiceImpl extends ServiceImpl<EmrProcessMapper, EmrProcess> implements EmrProcessService {

    @Autowired
    private EmrProcessDetailService emrProcessDetailService;

    @Autowired
    private EmrProcessDetailUserService emrProcessDetailUserService;
    @Autowired
    private EmrItemStandardTaskService emrItemStandardTaskService;

    @Override
    public Result findEmrTaskList(String keyvalue) {
        //获取明细表
        List<EmrProcessDetail> detailList = emrProcessDetailService.list(new LambdaQueryWrapper<EmrProcessDetail>().eq(EmrProcessDetail::getDelFlag, 0));
        Map<String, List<EmrProcessDetail>> deatailMap = detailList.stream().collect(Collectors.groupingBy(EmrProcessDetail::getProcessCode));


        MPJLambdaWrapper<EmrProcess> wrapper = new MPJLambdaWrapper<>();
        wrapper.selectAll(EmrProcess.class);
        wrapper.selectAs(EmrVersion::getVersionName, EmrProcess::getVersionName);
        wrapper.selectAs(EmrGrade::getGradeName, EmrProcess::getGradeName);
        wrapper.leftJoin(EmrVersion.class, EmrVersion::getVersionCode, EmrProcess::getVersionCode);
        wrapper.leftJoin(EmrGrade.class, EmrGrade::getGradeCode, EmrProcess::getGradeCode);
        if (StringUtils.isNotBlank(keyvalue)) {
            wrapper.and(item -> item.like(EmrProcess::getProcessName, keyvalue).or().like(EmrProcess::getProcessCode, keyvalue));
        }
        wrapper.eq(EmrProcess::getDelFlag, 0);
        List<EmrProcess> list = this.list(wrapper);
        for (EmrProcess emrProcess : list) {
            List<EmrProcessDetail> details = deatailMap.get(emrProcess.getProcessCode());
            //获取明细表DETATIL_STATUS字段 为1的数量
            long count = details.stream().filter(item -> "1".equals(item.getDetatilStatus())).count();
            emrProcess.setFinishData(count);
            emrProcess.setSumData(details.size());

        }
        return Result.succ(1, "获取信息成功", list);
    }

    @Override
    public Result findEmrTaskListByUser(String keyvalue) {
        SysUser sysUser = RedisUserManager.getUser();
        if (Objects.isNull(sysUser) || StringUtils.isBlank(sysUser.getUsername())) {
            return Result.fail("未找到当前用户信息");
        }
        //获取明细表
        List<EmrProcessDetail> detailList = emrProcessDetailService.list(new LambdaQueryWrapper<EmrProcessDetail>().eq(EmrProcessDetail::getDelFlag, 0));
        Map<String, List<EmrProcessDetail>> deatailMap = detailList.stream().collect(Collectors.groupingBy(EmrProcessDetail::getProcessCode));



        String username = sysUser.getUsername();

        MPJLambdaWrapper<EmrProcess> wrapper = new MPJLambdaWrapper<>();
        wrapper.distinct().selectAll(EmrProcess.class);
        wrapper.selectAs(EmrVersion::getVersionName, EmrProcess::getVersionName);
        wrapper.selectAs(EmrGrade::getGradeName, EmrProcess::getGradeName);
        wrapper.leftJoin(EmrVersion.class, EmrVersion::getVersionCode, EmrProcess::getVersionCode);
        wrapper.leftJoin(EmrGrade.class, EmrGrade::getGradeCode, EmrProcess::getGradeCode);
        wrapper.leftJoin(EmrProcessDetailUser.class, EmrProcessDetailUser::getProcessCode, EmrProcess::getProcessCode);
        if (StringUtils.isNotBlank(keyvalue)) {
            wrapper.and(item -> item.like(EmrProcess::getProcessName, keyvalue).or().like(EmrProcess::getProcessCode, keyvalue));
        }
        wrapper.eq(EmrProcessDetailUser::getUserCode, username);
        wrapper.eq(EmrProcess::getDelFlag, 0);
        List<EmrProcess> list = this.list(wrapper);
        for (EmrProcess emrProcess : list) {
            List<EmrProcessDetail> details = deatailMap.get(emrProcess.getProcessCode());
            //获取明细表DETATIL_STATUS字段 为1的数量
            long count = details.stream().filter(item -> "1".equals(item.getDetatilStatus())).count();
            emrProcess.setFinishData(count);
            emrProcess.setSumData(details.size());

        }
        return Result.succ(1, "获取信息成功", list);
    }

    @Override
    public Result addEmrTask(EmrProcess emrTask) {
        LocalDateTime now = LocalDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
        emrTask.setProcessCode(now.format(formatter));
        emrTask.setStatus("0");
        boolean save = this.save(emrTask);

        // 通过版本号和级别 获取任务
        MPJLambdaWrapper<EmrItemStandardTask> wrapper = new MPJLambdaWrapper<>();
        wrapper.selectAll(EmrItemStandardTask.class);
        wrapper.leftJoin(EmrItemStandard.class,  p -> p.eq(EmrItemStandard::getVersionCode, EmrItemStandardTask::getVersionCode)
                .eq(EmrItemStandard::getRoleCode, EmrItemStandardTask::getRoleCode)
                .eq(EmrItemStandard::getGradeCode, EmrItemStandardTask::getGradeCode)
                .eq(EmrItemStandard::getItemCode, EmrItemStandardTask::getItemCode)
                .eq(EmrItemStandard::getDelFlag, 0));
        wrapper.eq(EmrItemStandardTask::getVersionCode, emrTask.getVersionCode())
                .eq(EmrItemStandardTask::getGradeCode, emrTask.getGradeCode())
                .eq(EmrItemStandard::getIsLis, 1)
                .eq(EmrItemStandardTask::getDelFlag, 0);
        List<EmrItemStandardTask> taskList = emrItemStandardTaskService.list(wrapper);
        List<EmrProcessDetail> details = new ArrayList<>();
        for (EmrItemStandardTask emrItemStandardTask : taskList) {
            EmrProcessDetail detail = new EmrProcessDetail();
            detail.setProcessCode(emrTask.getProcessCode());
            detail.setProcessName(emrTask.getProcessName());
            detail.setStandardTaskId(emrItemStandardTask.getId());
            detail.setDetatilStatus("0");
            details.add(detail);
        }
        emrProcessDetailService.saveBatch(details);
        if (save) {
            return Result.succ(1, "保存成功", null);
        }
        return Result.fail("保存失败");
    }

    @Override
    public Result deleteEmrTask(List<EmrProcess> emrTask) {
        List<String> ids = emrTask.stream().map(EmrProcess::getId).collect(Collectors.toList());
        List<String> processCodes = emrTask.stream().map(EmrProcess::getProcessCode).collect(Collectors.toList());
        emrProcessDetailService.remove(new LambdaQueryWrapper<EmrProcessDetail>().in(EmrProcessDetail::getProcessCode, processCodes));
        emrProcessDetailUserService.remove(new LambdaQueryWrapper<EmrProcessDetailUser>().in(EmrProcessDetailUser::getProcessCode, processCodes));
        boolean b = this.removeByIds(ids);
        if (b) {
            return Result.succ(1, "删除成功", null);
        }
        return Result.fail("删除失败");
    }
}
